package com.ruoyi.video.server.rtsp;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.video.domain.VideoCamera;
import com.ruoyi.video.server.push.PushMessage;
import com.ruoyi.video.server.push.PushServer;
import com.ruoyi.video.server.utils.StreamUtils;
import com.ruoyi.video.service.IVideoCameraService;
import lombok.extern.slf4j.Slf4j;
import java.util.List;

/**
 * 独立的RTSP设备在线测试线程
 */
@Slf4j
public class RtspTestThread extends Thread{
    private IVideoCameraService videoCameraService;
    private PushServer pushServer;
    public static boolean running = false;
    @Override
    public void run() {
        if(running){
            log.info("上个RTSP检测进程未结束，本次任务将忽略");
            return;
        }
        log.info("开始RTSP检测进程...");
        running = true;

        videoCameraService = SpringUtils.getBean(IVideoCameraService.class);
        pushServer = SpringUtils.getBean(PushServer.class);

        VideoCamera vcc = new VideoCamera();
        vcc.setType(RtspServer.SERVER_CODE);
        List<VideoCamera> list = videoCameraService.selectVideoCameraList(vcc);
        if(StringUtils.isEmpty(list)){
            running = false;
            log.info("RTSP检测进程结束");
            return;
        }
        try {
            for (VideoCamera videoCamera : list) {
                Boolean ol = StreamUtils.test(videoCamera.getRtsp());
                if (ol && videoCamera.getOnline().equalsIgnoreCase("N")) {
                    videoCamera.setOnline("Y");
                    videoCameraService.updateVideoCamera(videoCamera);
                    pushServer.push(PushMessage.DEVICE_ONLINE, videoCamera.getId(), videoCamera);
                } else if (!ol && videoCamera.getOnline().equalsIgnoreCase("Y")) {
                    videoCamera.setOnline("N");
                    videoCameraService.updateVideoCamera(videoCamera);
                    pushServer.push(PushMessage.DEVICE_OFFLINE, videoCamera.getId(), videoCamera);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("RTSP检测异常:{}", e);
        }
        log.info("RTSP检测进程结束");
        running = false;
    }

}
